package cn.source.web.controller.zk;


import cn.source.common.core.controller.BaseController;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.domain.entity.SysRole;
import cn.source.common.core.domain.entity.SysUser;
import cn.source.common.core.page.TableDataInfo;
import cn.source.common.utils.NumberUtils;
import cn.source.common.utils.SecurityUtils;
import cn.source.common.utils.poi.ExcelUtil;
import cn.source.system.service.ISysRoleService;
import cn.source.system.service.ISysUserService;
import cn.source.zk.domain.entity.*;
import cn.source.zk.domain.vo.SubstationConnectionPointVO;
import cn.source.zk.service.IZkAreaService;
import cn.source.zk.service.IZkConnectionPointService;
import cn.source.zk.service.IZkDeviceService;
import cn.source.zk.service.IZkSubstationService;
import com.alibaba.fastjson2.JSONObject;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 变电站相关接口
 */
@RestController
@RequestMapping("/zk/substation")
public class ZkSubstationController extends BaseController {

    @Autowired
    private IZkSubstationService substationService;

    @Autowired
    private IZkConnectionPointService connectionPointService;

    @Autowired
    private IZkDeviceService deviceService;

    @Autowired
    private IZkAreaService areaService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询变电站信息分页列表
     *
     * @param substation
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo listPage(Substation substation) {
        startPage();
        List<Substation> list = substationService.listPage(substation);
        return getDataTable(list);
    }

    @GetMapping("/points-latest-10")
    public AjaxResult getLatest10Points() {
        Map<String, Object> pointsLineData = substationService.getLatest10PointsLineData();
        return AjaxResult.success(pointsLineData);
    }

    @GetMapping("/type-stat")
    public AjaxResult getTypeStat() {
        List<SubstationTypeStatVO> distributionAndYoY = substationService.getTypeDistributionAndYoY();
        return AjaxResult.success(distributionAndYoY);
    }

    /**
     * 获取各地区变电站数量统计
     * 返回示例: [{"area":"北京","count":12}, {"area":"上海","count":8}]
     */
    @GetMapping("/count-by-area")
    public AjaxResult getCountByArea() {
        JSONObject countByArea = substationService.getSubstationCountByArea();
        return AjaxResult.success(countByArea);
    }

//    @GetMapping("/by-dimension")
//    public AjaxResult getStatsByDimension(@RequestParam String dimension) {
//        List<SubstationStatVO> statsByDimension = substationService.getStatsByDimension(dimension);
//        return AjaxResult.success(statsByDimension);
//    }

    /**
     * 获取不同变电站类型的设备数量（用于饼图）
     */
    @GetMapping("/devices-by-substation-type")
    public AjaxResult getDevicesBySubstationType(@RequestParam String dimension) {
        List<SubstationStatVO> statsByDimension = substationService.getStatsByDimension(dimension);
        return AjaxResult.success(statsByDimension);
    }

    @GetMapping("/region-pie")
    public AjaxResult getRegionPieData() {
        List<Map<String, Object>> forPieChart = substationService.getRegionCountForPieChart();
        return AjaxResult.success(forPieChart);
    }

    /**
     * 获取不同变电站类型的数量统计（用于饼图/柱状图）
     */
    @GetMapping("/substation-count-by-type")
    public AjaxResult getSubstationCountByType() {
        return AjaxResult.success(substationService.getSubstationCountByType());
    }

    @GetMapping("/monthly-additions")
    public AjaxResult getMonthlyAdditions(@RequestParam("timeRange") String timeRange) {
        return AjaxResult.success(substationService.getMonthlyAdditions(timeRange));
    }

    @GetMapping("listFold")
    public TableDataInfo listPageFold(Substation substation) {
        // 设置地区的所有子级id
        List<Long> child = areaService.getChild(substation.getAreaNum());
        substation.setAreaChildNums(child);

        List<SysRole> sysRoles = roleService.selectRolesListByUserId(SecurityUtils.getUserId());
        if (sysRoles.size() > 0) {
            SysRole sysRole = sysRoles.get(0);
            // 一级管理员
            if (sysRole.getRoleKey().equals("company")) {
                SysUser sysUserQueryParams = new SysUser();
                sysUserQueryParams.setCreateBy(SecurityUtils.getUsername());
                List<SysUser> sysUsers = userService.selectUserList(sysUserQueryParams);
                String createByStr = SecurityUtils.getUsername();
                if (sysUsers.size() > 0) {
                    String bufferStr = sysUsers.stream().map(m -> m.getUserName()).collect(Collectors.joining(","));
                    createByStr = createByStr + ',' + bufferStr;
                }
                substation.setCreateBy(createByStr);
            }
            // 普通管理员
            if (sysRole.getRoleKey().equals("common")) {
                substation.setCreateBy(SecurityUtils.getUsername());
            }

            // 一般人员
            if (sysRole.getRoleKey().equals("general")) {
                substation.setCreateBy(SecurityUtils.getUsername());
            }
        }

        startPage();
        List<SubstationConnectionPointVO> list = substationService.listPageFold(substation);

        return getDataTable(list);
    }

    /**
     * 新增变电站信息
     */
    @PostMapping()
    public AjaxResult add(@RequestBody Substation substation) {

        //检查变电站是否存在
        if (substationService.checkSubstationExist(substation.getSubstationName(), null)) {
            return AjaxResult.error("变电站" + substation.getSubstationName() + "已存在,新增失败");
        }

        substation.setCreateBy(getUsername());
        substation.setUpdateBy(getUsername());

        // 设置容量为四舍五入并保留3位小数;
        substation.setTotalCapacity(NumberUtils.random3(substation.getTotalCapacity()));

        List<Substation> list = new ArrayList<>();
        list.add(substation);

        return toAjax(substationService.add(list));
    }

    /**
     * 根据num查询变电站信息
     *
     * @param num
     * @return
     */
    @GetMapping("/{num}")
    public AjaxResult getByNum(@PathVariable Long num) {
        Substation substation = substationService.getByNum(num);
        return AjaxResult.success(substation);
    }

    /**
     * 修改变电站信息
     *
     * @param substation
     * @return
     */
    @PutMapping()
    public AjaxResult edit(@RequestBody Substation substation) {

        //检查变电站是否存在
        if (substationService.checkSubstationExist(substation.getSubstationName(), substation.getNum())) {
            return AjaxResult.error("变电站" + substation.getSubstationName() + "已存在,修改失败");
        }

        // 设置容量为四舍五入并保留3位小数;
        substation.setTotalCapacity(NumberUtils.random3(substation.getTotalCapacity()));

        substation.setUpdateBy(getUsername());
        List<Substation> list = new ArrayList<>();
        list.add(substation);
        return toAjax(substationService.edit(list));
    }

    @DeleteMapping("/{nums}")
    public AjaxResult removeBatch(@PathVariable List<Long> nums) {
        //判断点电站下没有并网点
        List<ConnectionPoint> connectionPoints = connectionPointService.getBySubstationNums(nums);
        if (!connectionPoints.isEmpty()) {
            return AjaxResult.error("变电站下存在并网带点，不能删除");
        }

        //判断变电站下有没有设备
        List<Device> devices = deviceService.getBySubstationNums(nums);
        if (!devices.isEmpty()) {
            return AjaxResult.error("变电站下存在设备，不能删除");
        }

        return toAjax(substationService.removeBatch(nums));
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, Substation substation) {
        List<SubstationConnectionPointVO> list =
                substationService.listPageFold(substation);
        ExcelUtil<SubstationConnectionPointVO> util = new ExcelUtil<SubstationConnectionPointVO>(SubstationConnectionPointVO.class);
        util.exportExcel(response, list, "变电站信息");
    }


}
